<template>
  <div class="dynamic-app-container">
    <WebViewApp v-if="appType === 'iframeApp'" :url="appUrl"></WebViewApp>
    <component 
      v-else-if="(appType === 'localApp' || appType === 'agent') && currentComponent" 
      :is="currentComponent"
      :systemPrompt="systemPrompt"
    ></component>
  </div>
</template>

<script>
import WebViewApp from '@/components/WebViewApp/index.vue'

export default {
  name: 'DynamicApp',
  components: {
    WebViewApp
  },
  data() {
    return {
      appType: '',
      appUrl: '',
      currentComponent: null,
      systemPrompt: '',
      registeredComponents: {}
    }
  },
  async created() {
    await this.registerAppComponents()
    this.loadAppData()
  },
  methods: {
    async registerAppComponents() {
      try {
        const modules = import.meta.glob('@/views/app/*/index.vue')
        for (const path in modules) {
          const componentName = path.match(/\/app\/(.+?)\/index\.vue$/)[1]
          const module = await modules[path]()
          this.registeredComponents[componentName] = module.default
        }
      } catch (error) {
        console.error('注册app组件时发生错误:', error)
      }
    },
    async loadAppData() {
      const appData = this.$route.query
      if (appData) {
        this.appType = appData.appType
        if (this.appType === 'iframeApp' && appData.appData) {
          try {
            if (!/^[A-Za-z0-9+/]*={0,2}$/.test(appData.appData)) {
              console.error('无效的base64编码字符串')
              return
            }
            const decodedData = decodeURIComponent(atob(appData.appData))
            const parsedAppData = JSON.parse(decodedData)
            this.appUrl = parsedAppData.url
          } catch (error) {
            console.error('解码appData时发生错误:', error)
          }
        } else if ((this.appType === 'localApp' || this.appType === 'agent') && appData.appData) {
          try {
            const decodedData = decodeURIComponent(atob(appData.appData))
            const parsedAppData = JSON.parse(decodedData)
            if (parsedAppData.component) {
              this.currentComponent = this.registeredComponents[parsedAppData.component]
              if (!this.currentComponent) {
                console.error('未找到对应的本地组件:', parsedAppData.component)
              }
              if (this.appType === 'agent' && parsedAppData.systemPrompt) {
                this.systemPrompt = parsedAppData.systemPrompt
              }
            }
          } catch (error) {
            console.error('加载本地组件时发生错误:', error)
          }
        }
      }
    }
  },
  watch: {
    '$route.query': {
      handler() {
        this.loadAppData()
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.dynamic-app-container {
  width: 100%;
  height: 100%;
  overflow: auto;
}
</style>
